const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const session = require('koa-generic-session')
const redis = require('koa-redis')
const cors = require('koa2-cors')
const {sessionInfo,cookeInfo,redisInfo,corsOrigin} = require('./config/config')

const index = require('./routes/index')
const adminRouter = require('./routes/admin')
const essayRouter = require('./routes/essay')

//跨域
app.use(cors({
  origin(ctx){
    return corsOrigin
  },
  credentials:true
}))
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))


//redis
app.keys = sessionInfo.keys;
app.use(session({
  key:sessionInfo.name,
  pirefix:sessionInfo.pirefix,
  cookie:cookeInfo,
  store:redis(redisInfo)
}))



// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(adminRouter.routes(), adminRouter.allowedMethods())
app.use(essayRouter.routes(), essayRouter.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
